//超级管理模块
const router = require('koa-router')()
router.prefix('/supermanage')
//1.审核用户注册信息
//2.角色管理-增删改查
//3.权限分配-为角色分配权限 收回角色权限
//4.用户管理-增删改查

//1.获取角色列表
router.get('/role', async (ctx, next) => {
    let countSql = "select count(*) from roles";
    let countResults = await ctx.db.EXCUTE(countSql, []);
    let total = countResults[0]["count(*)"];
    let pageSize = Number(ctx.request.query.size)
    let page = ctx.request.query.page
    let startRow = total > 0 ? ((page - 1) * pageSize) : 0;
    //实现分页限制查找
    let limitSql = `select * from roles order by role_id desc limit ${startRow},${pageSize}`;
    let results = await ctx.db.EXCUTE(limitSql, []);
    let obj = {
        length: total,
        results: results,
        status: 200
    }
    ctx.body = JSON.stringify(obj);
})

//2.添加角色
router.post('/role', async (ctx, next) => {
    let roleType = ctx.request.body.type;
    let roleDesc = ctx.request.body.desc;

    let sql = "insert into roles (role_type, role_desc) values('" + roleType + "', '" + roleDesc + "')";
    await ctx.db.EXCUTE(sql, []);
    let sql2 = `select * from roles where role_type = '${roleType}'`;
    let results = await ctx.db.EXCUTE(sql2, []);
    let roleId = results[0].role_id;
    let sql3 = `insert into rolelimit (role_id) values(${roleId})`;
    await ctx.db.EXCUTE(sql3, []);
    ctx.body = {
        "status": 200,
        "msg": '添加成功',
    }
})

//3.删除角色
router.delete('/role', async (ctx, next) => {
    let sql = `delete from roles where role_id=${ctx.request.body.roleId}`
    let results = await ctx.db.EXCUTE(sql, []);
    if (results.affectedRows > 0) {
        let obj = {
            status: 200,
            msg: '删除成功'
        }
        ctx.body = JSON.stringify(obj);
    }
})

//4.编辑角色
router.put('/role', async (ctx, next) => {
    let roleId = ctx.request.body.roleId;
    let roleType = ctx.request.body.type;
    let roleDesc = ctx.request.body.desc;
    let sql = `update roles set role_type = '${roleType}', role_desc = '${roleDesc}' WHERE role_id = ${roleId}`;
    await ctx.db.EXCUTE(sql, []);
    let obj = {
        msg: "编辑成功",
        status: 200
    }
    ctx.body = JSON.stringify(obj);
})

//6.添加用户
router.post('/users', async (ctx, next) => {
    let userName = ctx.request.body.userName;
    let userNumber = ctx.request.body.userNumber;
    let roleName = ctx.request.body.roleName;
    let sql = `select role_id from roles where role_desc = '${roleName}'`;
    let result = await ctx.db.EXCUTE(sql, []);
    let role_id = result[0].role_id;
    let sql2 = "insert into users (user_name, user_number,user_roleid) values('" + userName + "', '" + userNumber + "', '" + role_id + "')";
    await ctx.db.EXCUTE(sql2, []);
    ctx.body = {
        "status": 200,
        "msg": '添加成功',
    }
})

//7.删除用户
router.delete('/users', async (ctx, next) => {
    let sql = `delete from users where user_id=${ctx.request.body.userId}`
    let results = await ctx.db.EXCUTE(sql, []);
    if (results.affectedRows > 0) {
        let obj = {
            status: 200,
            msg: '删除成功'
        }
        ctx.body = JSON.stringify(obj);
    }
})

//8.修改用户
router.put('/users', async (ctx, next) => {
    let userId = ctx.request.body.userId;
    let userName = ctx.request.body.userName;
    let pwd = ctx.request.body.pwd;
    let number = ctx.request.body.number;
    let roleName = ctx.request.body.roleName;
    let sql = `select role_id from roles where role_desc = '${roleName}'`;
    let result = await ctx.db.EXCUTE(sql, []);
    let role_id = result[0].role_id;
    let sql2 = `update users set user_name = '${userName}', user_pwd = '${pwd}',user_roleid = ${role_id},user_number = ${number} WHERE user_id = ${userId}`;
    await ctx.db.EXCUTE(sql2, []);
    let obj = {
        msg: "编辑成功",
        status: 200
    }
    ctx.body = JSON.stringify(obj);
})

//9.查找用户-显示用户列表
router.get('/users', async (ctx, next) => {
    let name = ctx.request.query.name;
    let countSql = name ? `select count(*) from users where user_name like '%${name}%'` : "select count(*) from users";
    let countResults = await ctx.db.EXCUTE(countSql, []);
    let total = countResults[0]["count(*)"];
    let pageSize = Number(ctx.request.query.size)
    let page = ctx.request.query.page
    let startRow = total > 0 ? ((page - 1) * pageSize) : 0;
    //实现分页限制查找
    let limitSql = name ? `select * from users where user_name like '%${name}%' order by user_id desc limit ${startRow},${pageSize}` : `select * from users order by user_id desc limit ${startRow},${pageSize}`;
    let results = await ctx.db.EXCUTE(limitSql, []);
    for (let i = 0; i < results.length; i++) {
        let sql = `select role_desc from roles where role_id = ${results[i].user_roleid}`;
        let res = await ctx.db.EXCUTE(sql, []);
        let roleName = res[0].role_desc;
        results[i].roleName = roleName;
    }
    let obj = {
        length: total,
        results: results,
        status: 200
    }
    ctx.body = JSON.stringify(obj);
})

//获取所有权限
router.get('/limits', async (ctx, next) => {
    let sql = `select * from authority`;
    let results = await ctx.db.EXCUTE(sql, []);

    const transformedData = [];
    let currentTitle = "";
    let currentAuthorities = [];

    results.forEach((item) => {
        const title = item.authority_title;

        if (title !== currentTitle) {
            if (currentAuthorities.length > 0) {
                transformedData.push({ authority_title: currentTitle, authorities: currentAuthorities });
            }
            currentTitle = title;
            currentAuthorities = [];
        }

        currentAuthorities.push({
            authority_id: item.authority_id,
            authority_name: item.authority_name,
            authority_path: item.authority_path,
            authority_desc: item.authority_desc
        });
    });

    // 添加最后一组数据
    if (currentAuthorities.length > 0) {
        transformedData.push({ authority_title: currentTitle, authorities: currentAuthorities });
    }
    if (results) {
        let obj = {
            status: 200,
            results: transformedData
        }
        ctx.body = JSON.stringify(obj);
    }
})

//获取选定角色当前拥有的权限
router.get('/rolelimits', async (ctx, next) => {
    let id = ctx.request.query.roleId;
    let sql = `select * from rolelimit where role_id = ${id}`;
    let results = await ctx.db.EXCUTE(sql, []);
    let obj = {
        results: results,
        status: 200
    }
    ctx.body = JSON.stringify(obj);
})

//编辑选定角色的权限
router.put('/rolelimits', async (ctx, next) => {
    let id = ctx.request.body.roleId;
    let authority = ctx.request.body.authority;
    let sql = `update rolelimit set authority_id = '${authority}' WHERE role_id = ${id}`;
    let results = await ctx.db.EXCUTE(sql, []);
    let obj = {
        results: results,
        status: 200
    }
    ctx.body = JSON.stringify(obj);
})

//13.获取用户权限
router.get('/userlimits', async (ctx, next) => {
    let roleId = ctx.request.query.roleId;
    let sql = `select authority_id from rolelimit where role_id=${roleId}`;
    let results = await ctx.db.EXCUTE(sql, []);
    let resArray = results[0].authority_id.split(",");
    let admitRequest = "";
    for (let i = 0; i < resArray.length; i++) {
        let sql = `select authority_path from authority where authority_id = ${Number(resArray[i])}`;
        let results = await ctx.db.EXCUTE(sql, []);
        admitRequest = admitRequest + results[0].authority_path;
    }
    let obj = {
        status: 200,
        results: results,
        //中间件进行admitRequest的验证
        admitRequest: admitRequest
    }
    ctx.body = JSON.stringify(obj);
})
module.exports = router
